// Minimal static server (no deps) for preview
const http = require('http');
const fs = require('fs');
const path = require('path');

const port = process.env.PORT ? Number(process.env.PORT) : 5173;
const root = __dirname;

const mime = {
  '.html': 'text/html; charset=utf-8',
  '.js': 'application/javascript; charset=utf-8',
  '.json': 'application/json; charset=utf-8',
  '.css': 'text/css; charset=utf-8',
  '.png': 'image/png',
  '.jpg': 'image/jpeg',
  '.jpeg': 'image/jpeg',
  '.svg': 'image/svg+xml',
};

function send(res, status, data, headers = {}) {
  res.writeHead(status, { 'Cache-Control': 'no-cache', ...headers });
  res.end(data);
}

const server = http.createServer((req, res) => {
  let urlPath = req.url.split('?')[0];
  if (urlPath === '/' || urlPath === '') urlPath = '/index.html';
  const filePath = path.join(root, urlPath);
  if (!filePath.startsWith(root)) return send(res, 403, 'Forbidden');
  fs.stat(filePath, (err, stat) => {
    if (err) return send(res, 404, 'Not Found');
    if (stat.isDirectory()) {
      const indexPath = path.join(filePath, 'index.html');
      return fs.readFile(indexPath, (err2, data2) => {
        if (err2) return send(res, 404, 'Not Found');
        send(res, 200, data2, { 'Content-Type': mime['.html'] });
      });
    }
    const ext = path.extname(filePath).toLowerCase();
    fs.readFile(filePath, (err3, data3) => {
      if (err3) return send(res, 500, 'Server Error');
      send(res, 200, data3, { 'Content-Type': mime[ext] || 'application/octet-stream' });
    });
  });
});

server.listen(port, () => {
  console.log(`Preview server running at http://localhost:${port}/`);
});